package com.example.oauth2.base.service.impl;

import com.example.oauth2.base.domain.SsoPermission;
import com.example.oauth2.base.domain.SsoRole;
import com.example.oauth2.base.domain.SsoUser;
import com.example.oauth2.base.repository.SsoUserRepository;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    SsoUserRepository ssoUserRepository;
    @Autowired
    SsoPermissionService ssoPermissionService;

    @Override
    public UserDetails loadUserByUsername(String userName) {
        if(StringUtils.isEmpty(userName)){
            throw new RuntimeException("userName 不能为空");
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String grant_type = request.getParameter("grant_type");
        SsoUser ssoUser = ssoUserRepository.findByUsername(userName);
        if(ObjectUtils.isEmpty(ssoUser)){
            throw new RuntimeException("ssoUser 不能为空");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (ssoUser != null) {
            // 获取用户授权
            List<SsoPermission> ssoPermissions = ssoPermissionService.selectByUserId(ssoUser.getId());
            // 声明用户授权
            ssoPermissions.forEach(ssoPermission -> {
                if (ssoPermission != null && ssoPermission.getEnname() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(ssoPermission.getEnname());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
        }

        return new User(ssoUser.getUsername(), ssoUser.getPassword(), grantedAuthorities);
    }
}
